<?php

namespace mybackend\controllers\official;

use Yii;
use yii\data\Pagination;
use yii\web\UploadedFile;
use mybackend\controllers\BaseController;
use common\entities\official\MediaEntity;
use common\support\OSS;
use common\entities\myhtsq\ActionCode;
use common\entities\official\DirEntity;
use yii\helpers\Html;

class MediaController extends BaseController {

    public $layout = '@app/views/official/layouts/main.php';

    public function __construct($id, $module, $config = []) {
        parent::__construct($id, $module, $config);
    }

    protected function roleAuthRules() {
        return [
            'actions' => ['Index', 'Edit', 'Delete', 'QuickSet'],
            'rules' => [
                [
                    'allow' => true,
                    'actionCodeMaps' => [
                        'Index' => ActionCode::OFFICIAL_MED_VIEW,
                        'Edit' => ActionCode::OFFICIAL_MED_VIEW,
                        'Delete' => ActionCode::OFFICIAL_MED_MOD,
                        'QuickSet' => ActionCode::OFFICIAL_MED_MOD,
                    ]
                ]
            ]
        ];
    }

    public function actionIndex() {
        if (Yii::$app->request->isAjax) {
            $keyword = Yii::$app->request->get('keyword', '');
            $status = Yii::$app->request->get('status', 1);
            $dir_id = Yii::$app->request->get('dir_id', '');
            $page = Yii::$app->request->get('page', 1);
            $page_size = Yii::$app->request->get('rows', 20);
            $sidx = Yii::$app->request->get('sidx', 'id');
            $sord = Yii::$app->request->get('sord', 'DESC');
            $data = [
                'total' => 1,
                'page' => $page,
                'records' => 0,
                'rows' => [],
            ];
            $query = MediaEntity::find()->with('dir');
            if ($keyword) {
                $query->andWhere("type='{$keyword}' or name like '%{$keyword}%'");
            }
            if ($dir_id) {
                $query->andWhere(['=', 'dir_id', $dir_id]);
            }
            if ($status != '') {
                $query->andWhere(['=', 'status', $status]);
            }
            $pages = new Pagination(['totalCount' => $query->count()]);
            $pages->setPageSize($page_size, true);
            foreach ($query->orderBy($sidx . ' ' . $sord)->offset($pages->offset)->limit($pages->limit)->all() as $key => $item) {
                $data['records'] = $pages->totalCount;
                $data['total'] = ceil($pages->totalCount / $page_size);
                $data['rows'][$key] = [
                    'id' => $item->id,
                    'cell' => [
                        $item->dir->name,
                        $item->name,
                        $item->fileFmt(),
                        \common\support\Helper::setupSize($item->size),
                        $item->image_info,
                        $item->type,
                        $item->status,
                        $item->created_time ? date('Y-m-d H:i:s', $item->created_time) : '',
                        $item->modified_time ? date('Y-m-d H:i:s', $item->modified_time) : '',
                    ]
                ];
            }
            echo json_encode($data);
            return Yii::$app->end();
        }

        return $this->render('index');
    }

    public function actionGetDirs() {
        return $this->json([
            'retCode' => 0,
            'data' => DirEntity::getOptions()
        ]);
    }

    public function actionEdit($id = null) {
        if (empty($id)) {
            $model = new MediaEntity();
            $model->loadDefaultValues();
            $model->created_time = time();
        } else {
            $model = MediaEntity::find()->where(['id' => $id])->one();
            $model->modified_time = time();
        }
        if (Yii::$app->request->isPost) {
            $model->setAttributes(Yii::$app->request->post('MediaEntity'));
            $model->resourcesFile = UploadedFile::getInstance($model, 'resourcesFile');
            if ($model->save()) {
                if ($model->resourcesFile instanceof UploadedFile) {
                    $file = $model->resourcesFile;
                    //以文件的md5值，做为文件名
                    $fileName = md5_file($file->tempName) . "." . $file->getExtension();
                    $key = 'cmsmedia/' . date("Ym") . "/" . $fileName;
                    OSS::upload($key, $file->tempName);
                    $url = OSS::getUrl($key);
                    if ($url) {
                        if (in_array($file->extension, array('jpg', 'gif', 'png', 'jpeg'))) {
                            list($width, $height) = getimagesize($file->tempName);
                            $model->image_info = $width . '*' . $height;
                        }
                        $model->file = $url;
                        $model->size = $file->size;
                        $model->type = $file->extension;
                        $model->update();
                    }
                }
                return Html::script('top.postCallback(' . json_encode([
                        'retCode' => 0,
                        'retMsg' => 'success'
                    ]) . ')');
            } else {
                return Html::script('top.postCallback(' . json_encode([
                        'retCode' => -1,
                        'retMsg' => Html::errorSummary($model, ['class' => 'errorSummary'])
                    ]) . ')');
            }
        }
        $data = [
            'model' => $model,
            'dirs' => DirEntity::getOptions()
        ];

        return $this->json([
            'retCode' => 0,
            'data' => $data
        ]);
    }

    public function actionDelete() {
        if (Yii::$app->request->isAjax) {
            $ids = explode(',', Yii::$app->request->post('id'));
            foreach ($ids as $id) {
                $model = MediaEntity::findOne($id);
                $model->status = 0;
                $model->save();
            }
        }
    }

    public function actionQuickSet() {
        $id = $_POST['id'];
        unset($_POST['id']);
        unset($_POST['oper']);
        $model = MediaEntity::find()->where(['id' => $id])->one();
        if (!$model) {
            echo json_encode(['status' => false, 'errMsg' => \common\error\ErrorMsg::getDefaultMsg()]);
            return Yii::$app->end();
        }
        $model->setAttributes($_POST);
        $content = '';
        if (!$model->save()) {
            foreach ($model->getErrors() as $errors) {
                foreach ($errors as $error) {
                    if ($error != '')
                        $content.="{$error}";
                }
            }
            echo json_encode(['retCode' => 0, 'errMsg' => $error]);
            return Yii::$app->end();
        }
    }

}
